dofile("include/events.lua")

milena.behavior_event = {}
milena.mouse_event = {}
milena.key_event = {}
milena.timer_event = {}
milena.exit_event = {}

function milena.service.goto(href)
	if (href:find('action://'))~=1 then
		goto(href)
	else
		milena.service.execute(milena.service.execute(loadstring, href:sub(#'action://'+1, -1)))
	end
end

function milena.service.free_params(params)
	for k, v in pairs(params) do
		if type(v)=="table" and v.type=="HELEMENT" then
			v = nil
		end
	end
	params = nil
end

function milena.service.catch(evt, params, el, evts)
	for i, v in ipairs(evt) do
		milena.service.execute(v, params, el, evts)
	end
end

function milena.handle_event(params, he)
	if params.event=="behavior" then
		proc(behavior_loc, params, he, milena.event)
		if milena.event[params.cmd]=="HYPERLINK_CLICK" then
			milena.service.goto(he.href)
		elseif milena.event[params.cmd]=="MENU_ITEM_CLICK" then
			milena.service.goto(he.link)
		end
		milena.service.catch(milena.behavior_event, params, he, milena.event)
	elseif params.event=="mouse" then
		milena.handle_mouse(params, he)
	elseif params.event=="key" then
		milena.handle_key(params, he)
	elseif params.event=="exit" then
		milena.handle_exit(params, he)
	elseif params.event=="timer" then
		milena.handle_timer(params, he)
	end
	milena.service.free_params(params)
	he = nil
	collectgarbage("collect")
end

function milena.handle_mouse(params, he)
	proc(behavior_loc, params, he, milena.mouse)
	milena.service.catch(milena.mouse_event, params, he, milena.mouse)
end

function milena.handle_key(params, he)
	if milena.key[params.cmd] == "KEY_DOWN" then
		local a = params.key_code
		milena.lastkey = a
		previous_key = a
		milena.key_press = true
		proc(key_pressed, a)
	end
	local f = milena.on_key or function () end
	f()
	proc(behavior_loc, params, he, milena.key)
	milena.service.catch(milena.key_event, params, he, milena.key)
end
function milena.handle_timer()
	proc(timer_loc)
	local f = milena.on_pause or function () end
	f()
	milena.service.catch(milena.timer_event)
end
function milena.handle_exit()
	for k, v in pairs(milena.exit) do
		v()
	end
	milena.service.catch(milena.exit_event)
end
function milena.quest_loaded()
--SPLASH
	if not element.get "img.milena_splash" then
		element.get('body'):set_html(('<img.milena_splash style="width: 250; height: 250; position: fixed; left: *; right: *; top: *; bottom: *;" fade-out src=%q/>'):format(milena.startdir..'/scripts/images/logo.png'), 2)
	end
end
